import WqRequest from "./request";
import { BASE_URL, TIME_OUT } from "./request/config";
import router from "@/router/index";

let isTime = true;

export default new WqRequest({
    baseURL: BASE_URL,
    timeout: TIME_OUT,
    AccessControlAllowOrigin: "*",
    Interceptors: {
        requestInterceptor(config) {
            if (localStorage.getItem("token")) {
                if (config.headers) {
                    config.headers.eceibstoken = localStorage.getItem("token");
                }
            }
            return config;
        },
        requestInterceptorCatch: (err) => {
            console.log(err);
        },
        responseInterceptor: (config) => {
            if (config.data.code === 401) {
                setMessage("登录过期");
                router.replace("/login");
            } else if (!config.data.code) {
                return config;
            } else if (config.data.code !== 200) {
                setMessage(config.data.message);
            }
            return config;
        },
        responseInterceptorCatch: (err) => {
            if (err.code === "ECONNABORTED" && err.message.indexOf("timeout") !== -1) {
                setMessage("网络超时");
            }
            if (err.code === "ERR_BAD_RESPONSE" && err.message === "Request failed with status code 500") {
                setMessage("服务器错误");
            }
            if (err.code === "ERR_NETWORK" && err.message === "Network Error") {
                setMessage("网络错误");
            }
            if (err.code === "ERR_BAD_REQUEST" && err.message === "Request failed with status code 401") {
                setMessage("登录过期");
                router.replace("/login");
            }
            console.log(err);
        }
    }
});

function setMessage(message) {
    isTime &&
        ElMessage({
            message,
            type: "error"
        });
    isTime = false;
    setTimeout(() => {
        isTime = true;
    }, 3000);
}
